<?php

namespace app\api\controller;

use app\api\controller\Login;
use think\Request;
use think\Db;
use think\Controller;
use think\Cache;
class Sendmess extends Controller{
 //状态码 0成功 100没有携带参数  101请传入用户uid 400失败 
    private $code = [0,100,101,400,102];

  private $appid = 'wx49d5ef2a0bda35a4';
    private $AppSecret = '39f9b7f0d5cf4df0cfb0a3f7c47accaf';
  private $template_arr = 'xHet154ulenBa_E29fE7I1puPWLctbUIweNBAS8WaUw';
  public function send_msg($touser,$page,$form_id,$value){
                $access_token = $this->get_accessToken();
                
                $template_id = $this->template_arr;
                
                $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
                $dd = array();
                //$dd['access_token']=$access_token;
                $dd['touser']=$touser;
                $dd['template_id']=$template_id;
                $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
                $dd['form_id']=$form_id;
                
                $dd['data']=$value;                        //模板内容，不填则下发空模板
                
                $dd['color']='';                        //模板内容字体的颜色，不填默认黑色
                //$dd['color']='#ccc';
                $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
                //$dd['emphasis_keyword']='keyword1.DATA';
                
                //$send = json_encode($dd);   //二维数组转换成json对象
                
                /* curl_post()进行POST方式调用api： api.weixin.qq.com*/
                $result = $this->https_curl_json($url,$dd,'json');
                return $result;
                // if($result){
                //     return json_encode(array('state'=>5,'msg'=>$result));
                // }else{
                //     return json_encode(array('state'=>4,'msg'=>$result));
                // }
    }
  
    /* 发送json格式的数据，到api接口 -xzz0704  */
    public function https_curl_json($url,$data,$type){
        if($type=='json'){//json $_POST=json_decode(file_get_contents('php://input'), TRUE);
            $headers = array("Content-type: application/json;","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
            $data=json_encode($data,JSON_UNESCAPED_UNICODE);
      
        }else{
      
    }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
        $output = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl);
        return $output;
    }
  
  
  
  public function get_accessToken(){
        /* 在有效期，直接返回access_token */
        if(Cache::get('access_token')){
            return Cache::get('access_token');
      
        }
        /* 不在有效期，重新发送请求，获取access_token */
        else{
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->AppSecret.'';
      
            $result = $this->curl_get_https($url);
            
            if($result){
        Cache::set('access_token',$result['access_token'],7100);
                return Cache::get('access_token');
            }else{
                return 'err';
            }
        }
    }
  
  private function curl_get_https($url){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      $output = curl_exec($ch);
      curl_close($ch);
        $jsoninfo = json_decode($output, true);
      return $jsoninfo;
   }

   function saveformid(){
        $request = Request::instance();
        $post = $request->post();
        if (empty($post["uid"])){
            return json(['code'=>($this->code[2]),'msg'=>'未携带用户uid','data'=>null]);
        }
        if (empty($post["formid"])){
            return json(['code'=>($this->code[2]),'msg'=>'未携带formid','data'=>null]);
        }
        $post["create_time"] = time();
        $post["status"] = 0;
        $taskid = Db::name('form')->insertGetId($post);
        return json(['code'=>($this->code[0]),'msg'=>'添加formid成功','data'=>["taskid" => $taskid]]);

   }

   //判断form_id是否过期
function form($uid)
{
   //$mysql = new Mysql();
   $formid = DB::name("form")->where(["uid"=>$uid,"status"=>0])->select();
   
   if(empty($formid))
   {
      return false;
   }
   $formId = $formid[0];
   $create_time = $formId['create_time'];
   $now_time = time();
   $cha_time = $now_time-($create_time+60*60*24*7);
   if($cha_time>0)
   {
      $data = array(
         'status'=> '2'
      );
      $res=DB::name("form")->where("formid",$formId["formid"])->update($data);
      if($res)
      {
         return $this->form($uid);
      }

   }else{
        $data = array(
             'status'=> '1'
          );
        $res=DB::name("form")->where("formid",$formId["formid"])->update($data);
      return $formId['formid'];
   }
}

function pushMess(){
    $now_time = time();
    $left_time = $now_time-10;
    $right_time = $now_time+10;
    $where["is_notice"] = 0;
    $where["notice"] = ['>',$left_time];
    $where["notice"] = ['<',$right_time];
    $noticeTimes = DB::name("notice")->where("is_notice",0)->where('notice','>',$left_time)->where('notice','<',$right_time)->select();
    //->where(["is_notice"=>0])->where('notice','>',$left_time)->where('notice','<',$right_time)
    if ($noticeTimes==null){
         return json(['code'=>400,'msg'=>'暂无信息发送', 'data' => null]);
    }
    foreach($noticeTimes as $k=>$v){
        $task = DB::name("task")->where(["id"=>$v["task_id"]])->select();
        
        // $keyword1 = $v["nick"];  //提醒人匿名
        // $keyword2 = $task[0]["text"];
        // $keyword3 = date("Y-m-d H:i:s",$task[0]["notice_time"]);  //提醒时间
        // $keyword4 = "完成后别忘记打卡呦";

        $value = array(
                    "keyword1"=>array(
                    "value"=>$v["nick"],
                    "color"=>"#4a4a4a"
                    ),
                    "keyword2"=>array(
                        "value"=>$task[0]["text"],
                        "color"=>"#9b9b9b"
                    ),
                    "keyword3"=>array(
                        "value"=>date("Y-m-d H:i:s",$v["notice"]),
                        "color"=>"#9b9b9b"
                    ),
                    "keyword4"=>array(
                        "value"=>"完成后别忘记打卡呦",
                        "color"=>"#9b9b9b"
                    )
                );
        $touser = $v["openid"];
        $page = "pages/taskInfo/taskinfo?id=".$v["task_id"];
        //var_dump($touser);
        $form_id = $this->form($v["uid"]);
        if($form_id==false){
            return json(['code'=>($this->code[2]),'msg'=>'无可用formid','data'=>null]);
        }

        $result = $this->send_msg($touser,$page,$form_id,$value);
        
        $data = array(
        'is_notice'=>'1'
        );
        DB::name("notice")->where("id",$v["id"])->update($data);
        DB::name("task")->where("id",$v["task_id"])->update([
                      'is_end'=>0
              ]);



    }
    return json(['code'=>0,'msg'=>'信息发送成功']);

}


}

